package cn.owen.controller;


import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;

import cn.owen.config.CustomizedToken;
import cn.owen.config.LoginType;
import cn.owen.model.User;
import cn.owen.service.UserService;
import cn.owen.util.CurrentUserUtils;
import cn.owen.util.MD5Utils;
/**
 * 测试主页
 * @author wangwenbao
 *
 */
@Controller
@Scope(value="prototype")
public class IndexController {
	 @Autowired
	 private UserService userService;
	 
	 private Logger logger = Logger.getLogger(UserController.class);
	 @RequestMapping("/admin/index")
	 public String index(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
		 User user=CurrentUserUtils.getInstance().getUser();
		 model.addAttribute("user", user);
        return "admin/home";
	 }
	 /**
	  * 登录 跳转到后台首页
	  * @param name
	  * @param password
	  * @param model
	  * @param redirect
	  * @return
	  */
	 @RequestMapping("/admin/login")
	 public String Login(@RequestParam(value="name", required=false) String name,@RequestParam(value="password", required=false) String password, Model model,RedirectAttributes redirect,HttpServletRequest request) {
		 if (StringUtils.isEmpty(name)) {
			 return "redirect:/admin/login.htm";
		 }
		 Subject subject = SecurityUtils.getSubject();
		 if (!subject.isAuthenticated()) {
			CustomizedToken token = new CustomizedToken(name, password, LoginType.USER.toString());
			try {
				subject.login(token);
				User user = userService.selectByName(name);
				CurrentUserUtils.getInstance().setUser(user);
				//loginLog(user,"登录系统",request);
		    	return "redirect:/admin/index";
			} catch (AuthenticationException e) {
				logger.debug(e.getMessage());
				redirect.addFlashAttribute("err_code", e.getCause());
				return "redirect:/admin/login.htm";
			}
		}
		 /*User user=new User();
		 try {
			 password=MD5Utils.getMD5StringBySign(password);
    		 user = userService.getUserInfo(name,password);
    		 if(user==null){
    			 redirect.addFlashAttribute("err_code", "用户名密码错误");
    			 redirect.addFlashAttribute("user", null);
    			 return "redirect:/admin/login.htm";
    		 }else if(user.getStatus() == 2){
    			 redirect.addFlashAttribute("err_code", "此帐号已停用");
    			 redirect.addFlashAttribute("user", null);
    			 return "redirect:/admin/login.htm";
    		 }
		} catch (Exception e) {
			logger.debug(e.getMessage());
			redirect.addFlashAttribute("err_code", e.getMessage());
			redirect.addFlashAttribute("user", null);
			return "redirect:/admin/login.htm";
		}
		CurrentUserUtils.getInstance().setUser(user);
		loginLog(user,"登录系统",request);*/
    	return "redirect:/admin/index";
    }
	 /**
	  * 系统登录日志
	  * @param u
	  * @param log
	  * @param request
	  */
	/*private void loginLog(User u,String log,HttpServletRequest request) {
		Systemlog systemlog = new Systemlog();
		systemlog.setTitle(log);
		systemlog.setContent(log);
		systemlog.setAccount(u.getName());
		systemlog.setType(1);
		systemlog.setLoginIP(AddressUtils.getIp(request));
		String address = null;
		if(!systemlog.getLoginIP().equals("127.0.0.1") && !systemlog.getLoginIP().equals("localhost")){
			//获取指定IP的区域位置
			try {
				address = AddressUtils.getAddresses("ip=" + systemlog.getLoginIP(), "utf-8");
			} catch (Exception e) {
				e.printStackTrace();
			}
			systemlog.setLoginArea(address);
			//异地登陆的判断方法为：先比较本次登陆和上次登陆的区域位置，如果不一致，说明是异地登陆；如果获取不到区域，则比较IP地址，如果IP地址和上次的不一致，则是异地登陆
			Systemlog firstSystemlog = systemLogService.selectFirstOne(u.getName());
			if(firstSystemlog!=null){
				if(StringUtils.isNotBlank(address) && StringUtils.isNotBlank(firstSystemlog.getLoginArea())){
					if(!address.equals(firstSystemlog.getLoginArea())){
						systemlog.setDiffAreaLogin(Systemlog.systemlog_diffAreaLogin_y);
					}
				}else if(StringUtils.isNotBlank(systemlog.getLoginIP()) && StringUtils.isNotBlank(firstSystemlog.getLoginIP())){
					if(!systemlog.getLoginIP().equals(firstSystemlog.getLoginIP())){
						systemlog.setDiffAreaLogin(Systemlog.systemlog_diffAreaLogin_y);
					}
				}
			}
		}
		//systemLogService.insert(systemlog);
	}*/
	/**
	 * 登录后跳转到首页
	 * @param name
	 * @param model
	 * @return
	 */
    @RequestMapping("/admin/home")
    public String home(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
    	return "admin/home";
    }
    @RequestMapping("/admin/login.htm")
    public String toLogin(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
    	return "admin/login";
    }
    /**
     * 退出
     * @return
     */
    @RequestMapping("/admin/loginout")
    public String LoginOut(HttpServletRequest request) {
    	User user=CurrentUserUtils.getInstance().getUser();
    	//CurrentUserUtils.getInstance().setUser(null);
    	Subject subject = SecurityUtils.getSubject();
    	subject.logout();
    	//loginLog(user,"退出",request);
    	return "admin/login";
    }
    /**
     * 跳转到修改密码页面
     * @return
     */
    @RequestMapping("/admin/touppass")
    public String ToUpdatePassWord() {
    	return "admin/uppassword";
    }
    /**
     * 修改密码
     * @return
     */
    @RequestMapping("/admin/updatepass")
    @ResponseBody
    public String UpdatePassWord(@RequestParam(value="oldPassword", required=true) String oldPassword,@RequestParam(value="newPassword", required=true) String newPassword, Model model) {
    	User user=CurrentUserUtils.getInstance().getUser();
    	JSONObject json=new JSONObject();
    	String password=user.getPassword();
    	oldPassword=MD5Utils.getMD5StringBySign(oldPassword);
    	if(password.equals(oldPassword)){
    		user.setPassword(MD5Utils.getMD5StringBySign(newPassword));
    		userService.updateUserPass(user);
        	json.put("success", true);
        	json.put("memo","密码修改成功");
    	}else{
    		json.put("success", false);
        	json.put("memo","原密码不正确");
    	}
    	return json.toString();
    }
}
